package com.xujf.sym.model.api;

import android.util.Log;

import com.xujf.sym.BuildConfig;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public final class ApiClient {

    private ApiClient() {}

    public static final ApiService service = new Retrofit.Builder()
            .baseUrl(ApiDefine.API_BASE_URL)
            .client(new OkHttpClient.Builder()
                    .addInterceptor(createUserAgentInterceptor())
                    .addInterceptor(createHttpLoggingInterceptor())
                    .build())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiService.class);

//    private static Interceptor createUserAgentInterceptor() {
//        return new Interceptor() {
//
//            private static final String HEADER_USER_AGENT = "User-Agent";
//
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//                Request.Builder builder = chain.request().newBuilder();
//                OkHttpHackUtils.addRequestHeaderLenient(builder, HEADER_USER_AGENT, ApiDefine.USER_AGENT);
//                return chain.proceed(builder.build());
//            }
//
//        };
//    }

    private static Interceptor createUserAgentInterceptor() {
        return new Interceptor() {

            private static final String NAME_USER_AGENT = "User-Agent";

            @Override
            public Response intercept(Chain chain) throws IOException {
                return chain.proceed(chain.request().newBuilder()
                        .header(NAME_USER_AGENT, ApiDefine.USER_AGENT)
                        // TODO: 2018/4/15  
//                        .header("Cookie", "b3log-latke="+ LoginShared.getToken(AppController.getApplication()))
                        .build());
            }

        };
    }

    private static Interceptor createHttpLoggingInterceptor() {
        return new Interceptor() {
            private final Charset UTF8 = Charset.forName("UTF-8");

            @Override
            public Response intercept(Chain chain) throws IOException {

                if (BuildConfig.DEBUG) {
                    Request request = chain.request();
                    RequestBody requestBody = request.body();

                    String body = null;

                    if (requestBody != null) {
                        Buffer buffer = new Buffer();
                        requestBody.writeTo(buffer);

                        Charset charset = UTF8;
                        MediaType contentType = requestBody.contentType();
                        if (contentType != null) {
                            charset = contentType.charset(UTF8);
                        }
                        body = buffer.readString(charset);
                    }
                    Log.i("HttpInfo", "发送请求:method：" + request.method() + "->url：" + request.url() + "\nheaders:" + request.headers() + "->body:" + body);

                    long startNs = System.nanoTime();
                    Response response = chain.proceed(request);
                    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

                    ResponseBody responseBody = response.body();
                    String rBody = null;

                    if (responseBody != null) {
                        BufferedSource source = responseBody.source();
                        source.request(Long.MAX_VALUE); // Buffer the entire body.
                        Buffer buffer = source.buffer();

                        Charset charset = UTF8;
                        MediaType contentType = responseBody.contentType();
                        if (contentType != null) {
                            try {
                                charset = contentType.charset(UTF8);
                            } catch (UnsupportedCharsetException e) {
                                e.printStackTrace();
                            }
                        }
                        rBody = buffer.clone().readString(charset);
                    }

                    Log.i("HttpInfo", "收到响应->code:" + response.code() + "|message:" + response.message() + "|tookMs:" + tookMs + "ms\n|请求url：" + response.request().url() +
                            "请求body：" + body + "\n|响应body：" + rBody);
                    return response;
                } else {
                    return chain.proceed(chain.request());
                }
            }
        };
    }

}
